package com.newasia.server.shiro;

import com.alibaba.fastjson.JSONObject;
import com.newasia.server.common.result.ManagementRetCode;
import com.newasia.server.common.result.ResponseData;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ShiroUserFilter extends UserFilter {

    /**
     * 该方法会在验证失败后调用，这里由于是前后端分离，后台不控制页面跳转
     * 因此重写改成传输JSON数据
     */
    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        saveRequest(request);
        //((HttpServletResponse)response).setStatus(401);
        ((HttpServletResponse)response).setHeader("Content-Type","application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ResponseData data = new ResponseData();
        data.setSuccess(false);
        data.setMessage(ManagementRetCode.NOT_LOG_IN.getMessage());
        data.setCode(ManagementRetCode.NOT_LOG_IN.getCode());
        out.append(JSONObject.toJSONString(data));
        out.flush();
        out.close();
        //redirectToLogin(request, response);
    }

    /*@Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        String loginUrl = getLoginUrl();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.getWriter().append(JSON.toJSONString("10010"));
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        WebUtils.issueRedirect(request, response, loginUrl);
    }*/
}
